package com.hmall.order.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.ResultDTO;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.OrderLogisticsService;
import com.hmall.order.service.OrderService;
import com.hmall.order.util.ThreadLocalUtil;
import com.hmall.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    //注入feign客户端,远程调用商品微服务,查询商品信息
    @Autowired
    private ItemClient itemClient;

    @Autowired
    private OrderMapper orderMapper;

    //注入userclient
    @Autowired
    private UserClient userClient;

    //注入OrderDetailService
    @Autowired
    private OrderDetailService orderDetailService;

    //注入OrderLogisticsService
    @Autowired
    private OrderLogisticsService orderLogisticsService;

    /**
     * 添加订单信息,返回订单id
     *
     * @param params 请求参数
     * @return 返回订单id
     */
    @Override
    public Long addOrder(RequestParams params) {
        //远程调用商品服务,查询商品信息
        Item item = itemClient.findItemById(params.getItemId());

        //拿到商品的单价
        Long price = item.getPrice();
        //拿到购买的数量
        Long num = params.getNum();
        //计算总价
        Long totalFee = num * price;
        //封装order对象
        Order order = new Order();
        //设置未支付状态
        order.setStatus(1);
        //设置订单价格
        order.setTotalFee(totalFee);
        //设置支付类型
        order.setPaymentType(params.getPaymentType());
        //设置用户id
        order.setUserId(ThreadLocalUtil.getUserId());

        //将order对象传递到mapper层
        this.save(order);

        //创建OrderDetail对象
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(item.getId());
        orderDetail.setNum(Math.toIntExact(params.getNum()));
        orderDetail.setName(item.getName());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());
        orderDetailService.save(orderDetail);

        //创建OrderLogistics对象
        //调用远程微服务userclient
        Address address = userClient.findAddresses(params.getAddressId());
        OrderLogistics logistics = new OrderLogistics();
        logistics.setOrderId(order.getId());
        logistics.setContact(address.getContact());
        logistics.setMobile(address.getMobile());
        logistics.setProvince(address.getProvince());
        logistics.setCity(address.getCity());
        logistics.setTown(address.getTown());
        logistics.setStreet(address.getStreet());
        orderLogisticsService.save(logistics);
        return order.getId();
    }

    /**
     * 订单支付
     *
     * @param orderId  订单编号
     * @param password
     * @return 返回结果对象
     */
    @Override
    public ResultDTO payMoney(Long orderId, String password) {
        Order order = getById(orderId);
        //判断订单的状态是否为1
        if (order.getStatus() != 1) {
            throw new RuntimeException("支付出现问题,订单状态不为1");
        }

        //获取用户id
        Long userId = ThreadLocalUtil.getUserId();
        //远程调用userclient微服务
        User user = userClient.findUserById(userId);

        JSONObject jsonObject = JSONObject.parseObject(password);
        String o = (String)jsonObject.get("password");
        //使用md5加密
        String passwordMd5 = DigestUtils.md5DigestAsHex(o.getBytes());
        //判断密码是否相等
        if (user.getPassword().equals(passwordMd5)) {
            //扣减余额
            Long balance = user.getBalance();
            Long totalFee = order.getTotalFee();
            //新的余额
            long newbalance = balance - totalFee;
            //修改用户信息
            userClient.updateUser(newbalance,userId);

            order.setStatus(2);
            //修改订单信息
            this.saveOrUpdate(order);
            return new ResultDTO();
        }
        throw new RuntimeException("支付密码有问题!");
    }

    /**
     * 根据订单id查询订单
     * @param id 订单编号
     * @return 返回订单对象
     */
    @Override
    public Order findOrderById(Long id) {
        return this.getById(id);
    }

    /**
     * 根据订单状态查询到订单
     * @param status 订单状态
     * @return
     */
    @Override
    public List<Order> findOrders(Integer status) {
        return orderMapper.findOrders(status);
    }
}
